package com.casic.modules.sys.api;

import com.alibaba.fastjson.JSONObject;
import com.casic.common.utils.api.ResultInfo;
import com.casic.modules.sys.controller.AbstractController;
import com.casic.modules.sys.entity.SysUserEntity;
import com.casic.modules.sys.entity.VO.SysAppversionVO;
import com.casic.modules.sys.service.SysAppversionService;
import com.casic.modules.sys.service.SysUserService;
import com.casic.modules.sys.shiro.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * app端用户管理控制类
 */
@RestController
@RequestMapping("/api/user/")
public class ApiUserController extends AbstractController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysAppversionService sysAppversionService;

    /**
     * app用户登陆
     * @param parameter
     * @return
     */
    @RequestMapping(value = "login" ,method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
    public JSONObject login(@RequestBody Map<String,Object> parameter,HttpServletResponse resp) throws Exception {
        UsernamePasswordToken token=null;
        //用户名
        String userName=(String)parameter.get("userName");
        //判断用户名
        if(StringUtils.isEmpty(userName)){
            return ResultInfo.error(ResultInfo.ISEMPTY,"用户名");
        }
        //密码
        String password=(String)parameter.get("password");
        //判断密码
        if(StringUtils.isEmpty(password)){
            return ResultInfo.error(ResultInfo.ISEMPTY,"密码");
        }
        //查询用户信息
        SysUserEntity user = sysUserService.queryActiveByUserName(userName);
        //判断用户是否存在
        if(StringUtils.isEmpty(user)){
            return ResultInfo.error( ResultInfo.USER_NONE);
        }
        try{
            Subject subject = ShiroUtils.getSubject();
            token = new UsernamePasswordToken(userName, password);
            subject.login(token);
            user.setPassword("");
            user.setSalt("");
            Cookie cookie = new Cookie("JSESSIONID",ShiroUtils.getSession().getId().toString());
            cookie.setMaxAge(30*24*60*60);
            resp.addCookie(cookie);
            JSONObject data = (JSONObject)  JSONObject.toJSON(user);

            SysUserEntity sysUserEntity = new SysUserEntity();
            sysUserEntity.setUsername(userName);
            sysUserService.updateLastLoginTime(sysUserEntity);

            return ResultInfo.success(data);
        }catch (IOException e) {
            e.printStackTrace();
            return ResultInfo.error( ResultInfo.LOGIN_FAILED);
        }catch (UnknownAccountException e) {
            e.printStackTrace();
            return ResultInfo.error(ResultInfo.LOGIN_FAILED,e.getMessage()+",");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return ResultInfo.error( ResultInfo.USERNAME_PASSWORD_ERROR);
        }catch (LockedAccountException e) {
            e.printStackTrace();
            return ResultInfo.error( ResultInfo.USERLOCKING);
        }catch (AuthenticationException e) {
            return ResultInfo.error( ResultInfo.LOGIN_FAILED);
        }
    }

    /**
     * app用户退出
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
    public JSONObject logout() {
        try{
            SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
            //验证是否登陆
            if(StringUtils.isEmpty(sysUserEntity)){
                return ResultInfo.error(ResultInfo.NO_LOGIN);
            }
            ShiroUtils.logout();
            return ResultInfo.success();
        }catch(Exception e){
            e.printStackTrace();
            return ResultInfo.error(ResultInfo.LOGIN_OUT_ERROR);
        }
    }

    /**
     * app修改密码
     * @param parameter
     * @return
     */
    @RequestMapping(value = "modifyPassword", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public JSONObject modifyPassword(@RequestBody Map<String,Object> parameter){
        try{
            SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
            //验证是否登陆
            if(StringUtils.isEmpty(sysUserEntity)){
                return ResultInfo.error(ResultInfo.NO_LOGIN);
            }
            String oldPassword=(String)parameter.get("oldPassword");
            //验证旧密码是否为空
            if(StringUtils.isEmpty(oldPassword)){
                return ResultInfo.error(ResultInfo.ISEMPTY, "原密码");
            }
            String newPassword=(String)parameter.get("newPassword");
            //验证新密码是否为空
            if(StringUtils.isEmpty(newPassword)){
                return ResultInfo.error(ResultInfo.ISEMPTY, "新密码");
            }
            //原密码
            oldPassword = ShiroUtils.sha256(oldPassword,sysUserEntity.getSalt());
            //验证原密码
            if(!sysUserEntity.getPassword().equals(oldPassword)){
                return ResultInfo.error( ResultInfo.OLD_PASSWORD_ERROR);
            }
            //新密码
            newPassword = ShiroUtils.sha256(newPassword,sysUserEntity.getSalt());
            sysUserService.updatePassword(sysUserEntity.getUserId(),oldPassword, newPassword);
            ShiroUtils.logout();
            return ResultInfo.success();
        }catch(Exception e){
            e.printStackTrace();
            return ResultInfo.error(ResultInfo.MODIFY_PASSWORD_ERROR);
        }
    }

    /**
     * app版本更新
     * @return
     */
    @RequestMapping(value = "version", method = RequestMethod.GET)
    public JSONObject version(HttpServletRequest request){
        JSONObject data=new JSONObject();
        try{
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + path + "/";
            SysAppversionVO sysAppversionVO=sysAppversionService.findVersion();
            data.put("version_code",sysAppversionVO.getApkCode());
            data.put("version_name", sysAppversionVO.getVersionName());
            data.put("version_download", basePath+"api/downloadApk");
            data.put("version_message", sysAppversionVO.getVersionMessage());
            data.put("file_name",sysAppversionVO.getVersionName()+sysAppversionVO.getVersionCode());
            return ResultInfo.success(data);
        }catch(Exception e){
            e.printStackTrace();
            return ResultInfo.error(ResultInfo.GET_APP_VERSION_ERROE);
        }
    }
}
